<?php

namespace backend\models;

use common\models\Project;
use common\models\ProjectPreEvaluationMortgage;
use common\models\ProjectUpdateLog;
use common\models\UserModel;
use Yii;

/**
 * This is the model class for table "project_pre_evaluation_seal".
 *
 * @property string $id
 * @property string $mortgage_id
 * @property string $mortgage_type
 * @property string $mortgage_address
 * @property string $mortgage_district
 * @property string $mortgage_building_area
 * @property string $mortgage_land_area
 * @property string $mortgage_owner
 * @property integer $is_first_mortgage
 * @property string $mortgage_future
 * @property string $mortgage_state
 * @property string $mortgage_seal_order
 * @property integer $is_first_seal
 * @property string $mortgage_seal_state
 * @property string $mortgage_other_seal_order
 * @property string $mortgage_other_seal_state
 * @property string $mortgage_code
 * @property integer $whether_exploration
 * @property string $other_warrants_code
 * @property string $created_at
 * @property integer $lock_user
 * @property string $lock_timestamp
 * @property string $maximum_mortgage
 * @property string $remaining_service_life
 * @property string $mortgage_order
 * @property string $mortgage_situation
 */
class ProjectPreEvaluationSeal extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'project_pre_evaluation_seal';
    }

    /*关联表（ly） 抵押物列表 project_pre_evaluation_value*/
    public function getValue()
    {
        return $this->hasOne(ProjectPreEvaluationValue::className(), ['ppes' => 'id']);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['mortgage_id'], 'required'],
            [['is_first_mortgage', 'is_first_seal', 'whether_exploration', 'lock_user'], 'integer'],
            [['mortgage_future', 'mortgage_state', 'mortgage_seal_order', 'mortgage_seal_state', 'mortgage_other_seal_order', 'mortgage_other_seal_state'], 'string'],
            [['created_at'], 'safe'],
            [['mortgage_type', 'mortgage_address', 'mortgage_district', 'mortgage_building_area', 'mortgage_land_area', 'mortgage_owner', 'mortgage_code', 'other_warrants_code', 'lock_timestamp', 'maximum_mortgage', 'remaining_service_life', 'mortgage_order', 'mortgage_situation'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'mortgage_id' => '抵押本息信息',
            'mortgage_type' => '抵押物类型',
            'mortgage_address' => '抵押物地址',
            'mortgage_district' => '所在区域',
            'mortgage_building_area' => '建筑面积（平米）',
            'mortgage_land_area' => '土地面积（平米）',
            'mortgage_owner' => '权属人',
            'is_first_mortgage' => '是否首押',
            'mortgage_future' => '后续抵押情况',
            'mortgage_state' => '抵/质押物情况',
            'mortgage_seal_order' => '抵押物查封顺序',
            'is_first_seal' => '是否首封',
            'mortgage_seal_state' => '抵押物查封情况',
            'mortgage_other_seal_order' => '非抵押物查封顺序',
            'mortgage_other_seal_state' => '非抵押物查封情况',
            'mortgage_code' => '抵押物编号',
            'whether_exploration' => '是否详勘',
            'other_warrants_code' => '他项权证号',
            'created_at' => '添加时间',
            'lock_user' => '上锁人',
            'lock_timestamp' => '上锁时间',
            'maximum_mortgage' => '最高抵押额度（元）',
            'remaining_service_life' => '剩余使用年限',
            'mortgage_order' => '抵押物抵押顺序',
            'mortgage_situation' => '抵押情况描述',
        ];
    }

    /**
     * @param $id 主键
     * @param $project_id 项目id
     * @param $changedAttributes 属性值
     * @param $userId 用户id
     * @param $module 项目修改日志module
     * @param $module_type 项目类型 1混合类，2抵押类
     * @param int $type 1为添加,2为修改，3为删除
     * @return array
     */
    public static function setUpdateLog($id, $project_id, $changedAttributes, $userId, $module/*, $module_type*/, $type)
    {
        $model = self::findOne((int)$id);
        if ($model === null) {
            return array('state' => false, 'msg' => '数据不存在');
        }
        $mortgagor = ProjectPreEvaluationMortgage::findOne($model->mortgage_id);
        if ($mortgagor === null) {
            return array('state' => false, 'msg' => '数据不存在');
        }
        $project = Project::findOne($mortgagor->project_id);
        if ($project === null) {
            return array('state' => false, 'msg' => '数据不存在');
        }

        if ($project->type != 2) {
            $project->type = 1;
        }

        $attributeLabels = $model->attributeLabels();
        $intAttributeLabels = ['mortgage_type', 'is_first_mortgage', 'is_first_seal', 'whether_exploration', 'lock_user'];
        $userInfo = (new UserModel())->getDepartmentUsersList();

        switch ($type) {
            case 1:
                $data = $changedAttributes;
                if (!empty($data)) {
                    $log = '新增';
                    foreach ($data as $key => $value) {
                        if ($value != '' && $key != 'mortgage_id') {
                            if (in_array($key, $intAttributeLabels)) {
                                switch ($key) {
                                    case 'mortgage_type':
                                        $title = Yii::$app->params['mortgageTypes3'];
                                        $arr = explode(',', trim($value, ','));
                                        $str = '';
                                        foreach ($arr as $v) {
                                            $str .= $title[(int)$v]['name'] . '，';
                                        }
                                        $value = mb_substr($str, 0, -1, 'utf-8');
                                        break;
                                    case 'is_first_mortgage':
                                        $title = Yii::$app->params['IsFirstMortgage'];
                                        $value = $title[(int)$value]['name'];
                                        break;
                                    case 'is_first_seal':
                                        $title = Yii::$app->params['IsFirstSeal'];
                                        $value = $title[(int)$value]['name'];
                                        break;
                                    case 'whether_exploration':
                                        $title = Yii::$app->params['WhetherExploration'];
                                        $value = $title[(int)$value]['name'];
                                        break;
                                    case 'lock_user':
                                        if ($value > 0) {
                                            $value = $userInfo[$value]['description'] . '—' . $userInfo[$value]['realname'];
                                        }
                                        break;
                                    default:
                                }
                            }
                            if ($attributeLabels[$key] != 'ID') {
                                $log .= "{$attributeLabels[$key]}：{$value}\n";
                            }
                        }
                    }
                }
                break;

            //编辑
            case 2:
                //判断数据是否发生改变
                $state = false;
                $data = array(); //修改后的数据
                foreach ($changedAttributes as $key => $value) {
                    if ($model->$key != $value && $model->$key != 'mortgage_id') {
                        $data[$key] = $value;
                        $state = true;
                    }
                }

                if (!$state) {
                    //return array('state' => true, 'msg' => '添加预评估信息非抵押物情况修改记录成功');
                    return array('state' => true, 'msg' => '没有做任何修改');
                }

                if (!empty($data)) {
                    $log = '';
                    //$log = '修改ID：' . $id . ',';
                    //$log = '修改ID为' . $id . '的立项信息数据,';
                    foreach ($data as $key => $value) {
                        if (in_array($key, $intAttributeLabels)) {
                            switch ($key) {
                                case 'mortgage_type':
                                    $title = Yii::$app->params['mortgageTypes3'];
                                    $arr = explode(',', trim($value, ','));
                                    $str = '';
                                    foreach ($arr as $v) {
                                        $str .= $title[(int)$v]['name'] . '，';
                                    }
                                    $value = mb_substr($str, 0, -1, 'utf-8');
                                    break;
                                case 'is_first_mortgage':
                                    $title = Yii::$app->params['IsFirstMortgage'];
                                    $value = $title[(int)$value]['name'];
                                    break;
                                case 'is_first_seal':
                                    $title = Yii::$app->params['IsFirstSeal'];
                                    $value = $title[(int)$value]['name'];
                                    break;
                                case 'whether_exploration':
                                    $title = Yii::$app->params['WhetherExploration'];
                                    $value = $title[(int)$value]['name'];
                                    break;
                                case 'lock_user':
                                    if ($value > 0) {
                                        $value = $userInfo[$value]['description'] . '—' . $userInfo[$value]['realname'];
                                    }
                                    break;
                                default:
                            }
                        }
                        $log .= "{$attributeLabels[$key]}：{$value}\n";
                    }
                }
                break;

            //删除
            case 3:
                //$log = "删除ID：{$id}，";
                $log = "删除记录，";
                break;
        }

        try {
            $time = date('Y-m-d H:i:s');
            $projectUpdateLog = new ProjectUpdateLog();
            if ($project->type != 2) {
                $project->type = 1;
            }
            $module_title_array = $projectUpdateLog->getModuleArrayTitle($project->type);
            $projectUpdateLog->project_id = $project_id;
            $projectUpdateLog->module = $module_title_array[$module];
            $projectUpdateLog->type = $project->type;
            $projectUpdateLog->created_at = $time;
            $projectUpdateLog->user_id = $userId;
            $projectUpdateLog->log = mb_substr($log, 0, -1, 'utf-8');
            $re1 = $projectUpdateLog->save();
            if (!$re1) {
                throw new \Exception('抵押物信息记录添加失败');
            }

            return array('state' => true, 'msg' => '添加抵押物信息修改记录成功');
        } catch (\Exception $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        } catch (\Throwable $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        }
    }

}
